package com.zhijian.medical.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Profiles;

public class SpringUtil {
    private static final Logger logger = LoggerFactory.getLogger(SpringUtil.class);

    private static ApplicationContext context;

    public SpringUtil(ApplicationContext context) {
        SpringUtil.context = context;
        logger.info("[spring ioc loading success");
    }

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) context.getBean(name);
    }

    public static String[] getBeanNames() {
        return context.getBeanDefinitionNames();
    }

    public static boolean isProfileActive(String profile) {
        return context.getEnvironment().acceptsProfiles(Profiles.of(profile));
    }

    public static String getProperty(String key) {
        return context.getEnvironment().getProperty(key);
    }

    public static String[] getProfiles() {
        return context.getEnvironment().getActiveProfiles();
    }

    /**
     * 将对象托管在spring容器内
     *
     * @param <T>
     * @param beanName
     * @param bean
     * @deprecated 不建议使用，推荐初始化时托管在容器内。第三方参考starter或import托管
     */
    public static <T> void registerBean(String beanName, T bean) {
        ConfigurableApplicationContext configContext = (ConfigurableApplicationContext) context;
        configContext.getBeanFactory().registerSingleton(beanName, bean);
    }
}
